import { useEffect, useRef, useState } from 'react'
import Taro, { FC, useRouter, useShareAppMessage } from '@tarojs/taro';
import { forkJoin, from, of, Subscription } from 'rxjs';
import { retryWhen, switchMap, tap } from 'rxjs/operators';

import { View, Text, Canvas, Button } from '@tarojs/components'
import "taro-ui/dist/style/components/button.scss" // 按需引入 
import { getWxaCode } from '@/utils/qcloudHelpers'
import { genericRetryStrategy } from '@/utils/rxHelpers';
import { useRoomUiFacade } from '@/hooks/useRoomUiFacade';

import './index.scss'

type CBType = Taro.getImageInfo.SuccessCallbackResult;

//直播分享
export const Share: FC = () => {
  //文件管理
  const fsm = Taro.getFileSystemManager();
  const [canvasObj, setCanvasObj] = useState()
  //获取路由对象
  const router = useRouter();
  const [roomFacade] = useRoomUiFacade();
  const refIdref = useRef("");  //小程序码

  const roomId = router.params.roomId || '';
  const roomName = decodeURIComponent(router.params.roomName || '');
  const picUrl = decodeURIComponent(router.params.picUrl || '');
  const startTime = decodeURIComponent(router.params.startTime || '');

  const canvas_bck = "https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/share-bck.png";
  const imgurl_bck = "https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/share__bck.png";
  // const imgurl_logo = "https://leconglive-wxapp-1301839528.file.myqcloud.com/wxIcon/logo_text.png";
  const imgurl_logo = ASSETS_PATH + '/share_title.png';

  //兼容不同设备像素
  const rate = parseFloat((Taro.getSystemInfoSync().windowWidth / 375).toFixed(3));

  // 绘制画布的全内容   
  const drawImage = (codeFilePath: string, imgInfo1: CBType, imgInfo2: CBType, imgInfo3: CBType, imgInfo4: CBType) => {
    const daysArr = startTime.split(' ');

    const days = daysArr[0] // xx-xx-xx
    const newDaysArr = days.split('-')
    const newDays = newDaysArr[1] + '月' + newDaysArr[2] + '日'

    const times = daysArr[1].substring(0, 5)
    const weeks = (dayStr) => {
      const dateArray = dayStr.split("-");
      const date = new Date(dateArray[0], parseInt(dateArray[1] - 1 + ''), dateArray[2]);
      return "星期" + "日一二三四五六".charAt(date.getDay());
    };

    // canvas单行文本溢出省略
    const drawText = (ctx, str, leftWidth, topHeight, maxWidth) => {
      let strWidth = ctx.measureText(str).width;
      const ellipsis = '...';
      const ellipsisWidth = ctx.measureText(ellipsis).width;
      if (strWidth <= maxWidth || maxWidth <= ellipsisWidth) {
        return ctx.fillText(str, leftWidth, topHeight);
      } else {
        let len = str.length;
        while (strWidth + ellipsisWidth >= maxWidth && len-- > 0) {
          str = str.slice(0, len);
          strWidth = ctx.measureText(str).width;
        }
        return ctx.fillText(str + ellipsis, leftWidth, topHeight);
      }
    }

    // 创建canvas对象
    const getCanvas = Taro.createSelectorQuery()
    getCanvas.select('#card-canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const _canvas = res[0].node
        const ctx = _canvas.getContext('2d')
        // console.log(_canvas, '画布对象', res[0]);

        const dpr = Taro.getSystemInfoSync().pixelRatio
        _canvas.width = res[0].width * dpr
        _canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)

        // 画布背景 img2
        const img2 = _canvas.createImage()
        img2.src = imgInfo2.path
        img2.onload = () => {
          ctx.drawImage(img2, 0, 0, 300 * rate, 470 * rate)
          bckImg()
        }
        // 为防止图片覆盖，采用同步调用
        const bckImg = () => {
          // 内容背景 img3
          const img3 = _canvas.createImage()
          img3.src = imgInfo3.path;
          img3.onload = () => {
            ctx.drawImage(img3, 20 * rate, 35 * rate, 255 * rate, 400 * rate)
            //绘制文字
            ctx.font = "18px PingFang SC"
            ctx.fillStyle = '#000'
            drawText(ctx, roomName, 35 * rate, 138 * rate, 215 * rate)
            ctx.restore()
            ctx.font = "12px PingFang SC"
            ctx.fillStyle = '#888'
            ctx.fillText('—— 直播时间 —— ', 41 * rate, 345 * rate)

            ctx.font = "14px PingFang SC"
            ctx.fillStyle = '#d20202'
            ctx.fillText(newDays, 28 * rate, 380 * rate)

            ctx.font = "14px PingFang SC"
            ctx.fillStyle = '#333'
            ctx.fillText(weeks(days) + ' ' + times, 88 * rate, 380 * rate)

            ctx.font = "10px PingFang SC"
            ctx.fillStyle = '#555'
            ctx.fillText('长按扫码  观看直播', 53 * rate, 407 * rate)
            ctx.restore()
            // 小程序logo
            const logo = _canvas.createImage()
            logo.src = imgInfo4.path
            logo.onload = () => {
              ctx.drawImage(logo, (300 - 80) / 2 * rate, 50 * rate, 80 * rate, 56 * rate)
            }
            // 直播间背景
            const img1 = _canvas.createImage()
            img1.src = imgInfo1.path
            img1.onload = () => {
              ctx.drawImage(img1, 30 * rate, 155 * rate, 235 * rate, 132 * rate);
            }
            // 小程序码
            const img5 = _canvas.createImage()
            img5.src = codeFilePath
            img5.onload = () => {
              ctx.drawImage(img5, 185 * rate, 345 * rate, 80 * rate, 80 * rate);
            }

            setCanvasObj(_canvas)
          }
        }
      })
  }

  //转发按钮
  const bckImg = picUrl + '?imageMogr2/thumbnail/660x540/pad/1'
  useShareAppMessage(res => {
    if (res.from === 'button') {
      // console.log(res, '按钮属性')
    }
    return {
      title: `${roomName}`,
      imageUrl: bckImg,
      path: `/pages/index/index?roomId=${roomId}&refId=${refIdref.current}`
    }
  })

  //保存图片  
  const saveCard = () => {
    Taro.canvasToTempFilePath({
      canvas: canvasObj,
      x: 0,
      y: 0,
      width: 300 * rate,
      height: 470 * rate,
      destWidth: 300 * rate * 3,
      destHeight: 470 * rate * 3,
      fileType: 'jpg',
      quality: 1,
      success: (res) => {
        Taro.saveImageToPhotosAlbum({
          filePath: res.tempFilePath
        }).then((imgRes) => {
          if (imgRes.errMsg === 'saveImageToPhotosAlbum:ok') {
            Taro.showToast({
              title: '图片保存成功',
              icon: 'none',
              duration: 1000,
            })
          } else {
            Taro.showToast({
              title: '图片保存失败',
              icon: 'none',
              duration: 1000,
            })
          }
        })
      }
    })


  }

  //TODO 第二个参数需要用数据库referal表的Id
  const code$ = roomFacade.getRefId(roomId)
    .pipe(
      tap(refId => refIdref.current = refId),
      switchMap((refId) => from(getWxaCode(roomId, refId, 'pages/liveRoom/LiveDetails/index')))
    )
  const imgInfo1$ = from(Taro.getImageInfo({ src: picUrl + '?imageMogr2/rradius/30' }));
  const imgInfo2$ = from(Taro.getImageInfo({ src: canvas_bck }));
  const imgInfo3$ = from(Taro.getImageInfo({ src: imgurl_bck }));
  const imgInfo4$ = from(Taro.getImageInfo({ src: imgurl_logo }));

  useEffect(() => {
    const subs: Subscription[] = [
      //TODO 没有则使用默认背景图片
      of(1)
        .pipe(
          tap(() => {
            Taro.showLoading({
              title: '图片加载中...',
              mask: true,
            })
          }),
          switchMap(() => forkJoin([code$, imgInfo1$, imgInfo2$, imgInfo3$, imgInfo4$])),
          // 默认重试2次，间隔3秒
          retryWhen(genericRetryStrategy({ maxRetryAttempts: 2, scalingDuration: 1000 }))
        )
        .subscribe({
          next: ([code, imgInfo1, imgInfo2, imgInfo3, imgInfo4]) => {
            Taro.hideLoading();

            //定义一个固定的文件名称
            const filePath = `${Taro.env.USER_DATA_PATH}/${roomId}.png`;
            const data = code as string;

            fsm.access({
              path: filePath,
              success: () => {
                // console.log("加载图片缓存地址: ", filePath)
                drawImage(filePath, imgInfo1, imgInfo2, imgInfo3, imgInfo4);
              },
              fail: () => {
                fsm.writeFile({
                  filePath, // 要写入的文件路径 (本地路径)
                  data, // 要写入的文本或二进制数据
                  encoding: "base64", // 指定写入文件的字符编码
                  success: () => {
                    // console.log("写入图片缓存: ", filePath)
                    drawImage(filePath, imgInfo1, imgInfo2, imgInfo3, imgInfo4);
                  },
                  fail: console.error
                })
              }
            })
          },
          error: () => {
            Taro.hideLoading();
            Taro.showToast({
              title: '图片获取异常，请重新打开分享页面',
              icon: 'none',
              duration: 3000
            })
          },
          complete: () => {
            Taro.hideLoading();
          }
        })
    ]

    return () => { subs.map(sub => sub.unsubscribe()) }
  }, [])

  // 绘制画布
  return (
    <View className='index'>
      {/* 绘制画布 */}
      <View className='canvas-wrap'>
        <Canvas
          id='card-canvas'
          type='2d'
          className='card-canvas'
          style={`width: ${300 * rate}px; height: ${470 * rate}px; background-color: #fff; border-radius: ${20 * rate}px; padding: 0px;`}
        ></Canvas>
      </View>
      {/* 分享区域 */}
      <View className='share-box'>
        <View className='box-top'>
          <View className='box-top-line'></View>
          <Text>分享至</Text>
          <View className='box-top-line'></View>
        </View>
        <View className='box-btn'>

          <View className='btn-share'>
            <Button openType='share' className='test-btn'></Button>
            <Text>微信好友</Text>
          </View>
          <View className='btn-share' onClick={saveCard}>
            <View className='btn-icon btn-pyq'></View>
            <Text>保存图片</Text>
          </View>
        </View>
      </View>
    </View>
  )
}
export default Share